package com.example.amazing_wangjj.controller;

import com.example.amazing_wangjj.pojo.SealSampleInfo;
import com.example.amazing_wangjj.service.SealSampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 封样桶控制器
 * 提供封样桶相关的REST API接口
 */
@RestController
@RequestMapping("/api/seal-sample")
public class SealSampleController {

    @Autowired
    private SealSampleService sealSampleService;

    /**
     * 申请封样桶编码
     * @param request 申请请求，包含企业编码、材料类型、适用月份等信息
     * @return 申请结果，包含申请状态和封样桶编码信息
     */
    @PostMapping("/apply")
    public Map<String, Object> applySealSample(@RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String companyCode = request.get("companyCode");
            String materialType = request.get("materialType");
            String applicableMonth = request.get("applicableMonth");
            // 如果请求中没有applyTime，设置为当前时间
            String applyTime = request.get("applyTime");
            if (applyTime == null || applyTime.isEmpty()) {
                applyTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
            }
            
            // 检查企业今天是否已经申请过
            if (sealSampleService.hasAppliedToday(companyCode, applyTime)) {
                result.put("success", false);
                result.put("message", "今天已经申请过封样桶编码，请明天再试");
                return result;
            }
            
            // 生成并保存封样桶编码（实际应用中应该有更复杂的生成逻辑）
            SealSampleInfo sealSampleInfo = new SealSampleInfo();
            sealSampleInfo.setCompanyCode(companyCode);
            sealSampleInfo.setMaterialType(materialType);
            sealSampleInfo.setApplicableMonth(applicableMonth);
            sealSampleInfo.setApplyTime(applyTime);
            
            // 生成瓶盖码和瓶身码（这里简化实现）
            String bottleCapCode = generateCode(companyCode, "CP");
            String bottleBodyCode = generateCode(companyCode, "PS");
            sealSampleInfo.setBottleCapCode(bottleCapCode);
            sealSampleInfo.setBottleBodyCode(bottleBodyCode);
            
            sealSampleService.save(sealSampleInfo);
            
            result.put("success", true);
            result.put("message", "申请成功");
            result.put("data", sealSampleInfo);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "申请失败：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * 批量申请封样桶编码
     * @param request 包含企业编码、数量、材料类型、适用月份等信息
     * @return 申请结果，包含申请状态和Excel文件路径
     */
    @PostMapping("/batch-apply")
    public Map<String, Object> batchApplySealSample(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String companyCode = (String) request.get("companyCode");
            Integer count = (Integer) request.get("count");
            String materialType = (String) request.get("materialType");
            String applicableMonth = (String) request.get("applicableMonth");
            // 如果请求中没有applyTime，设置为当前时间
            String applyTime = (String) request.get("applyTime");
            if (applyTime == null || applyTime.isEmpty()) {
                applyTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
            }
            
            // 检查企业今天是否已经申请过
            if (sealSampleService.hasAppliedToday(companyCode, applyTime)) {
                result.put("success", false);
                result.put("message", "今天已经申请过封样桶编码，请明天再试");
                return result;
            }
            
            // 批量生成封样桶信息
            List<SealSampleInfo> sealSampleInfos = new java.util.ArrayList<>();
            for (int i = 0; i < count; i++) {
                SealSampleInfo sealSampleInfo = new SealSampleInfo();
                sealSampleInfo.setCompanyCode(companyCode);
                sealSampleInfo.setMaterialType(materialType);
                sealSampleInfo.setApplicableMonth(applicableMonth);
                sealSampleInfo.setApplyTime(applyTime);
                
                // 生成瓶盖码和瓶身码
                String bottleCapCode = generateCode(companyCode, "CP" + i);
                String bottleBodyCode = generateCode(companyCode, "PS" + i);
                sealSampleInfo.setBottleCapCode(bottleCapCode);
                sealSampleInfo.setBottleBodyCode(bottleBodyCode);
                
                sealSampleInfos.add(sealSampleInfo);
            }
            
            // 保存并导出Excel
            String filePath = sealSampleService.saveAndExportExcel(sealSampleInfos);
            
            result.put("success", true);
            result.put("message", "批量申请成功");
            result.put("filePath", filePath);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量申请失败：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * 查询封样桶信息
     * @param companyCode 企业编码
     * @param page 页码
     * @param pageSize 每页大小
     * @return 查询结果
     */
    @GetMapping("/query")
    public Map<String, Object> querySealSample(@RequestParam String companyCode, 
                                              @RequestParam(defaultValue = "1") int page, 
                                              @RequestParam(defaultValue = "10") int pageSize) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建查询条件
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<SealSampleInfo> pageQuery = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, pageSize);
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<SealSampleInfo> queryWrapper = new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            queryWrapper.eq("company_code", companyCode);
            queryWrapper.orderByDesc("apply_time");
            
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<SealSampleInfo> resultPage = sealSampleService.page(pageQuery, queryWrapper);
            
            result.put("success", true);
            result.put("data", resultPage.getRecords());
            result.put("total", resultPage.getTotal());
            result.put("current", resultPage.getCurrent());
            result.put("pages", resultPage.getPages());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
        }
        return result;
    }
    
    /**
     * 生成封样桶编码
     * @param companyCode 企业编码
     * @param prefix 前缀
     * @return 生成的编码
     */
    private String generateCode(String companyCode, String prefix) {
        // 简化的编码生成逻辑，实际应用中应该有更复杂的生成规则
        String timestamp = String.valueOf(System.currentTimeMillis());
        return companyCode + "." + prefix + "." + timestamp.substring(timestamp.length() - 8);
    }
}